{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3a90c9b3",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 直接导入Python的内置基础数学库\n",
    "import math\n",
    "print(math.cos(math.pi))\n",
    "# 从math中导入cos函数和pi变量\n",
    "from math import cos, pi\n",
    "print(cos(pi))\n",
    "# 如果是个模块，在导入的时候可以起个别名，避免名字冲突或是方便懒得打字的人使用\n",
    "import math as m\n",
    "print(m.cos(m.pi))\n",
    "# 从math中导入所有东西\n",
    "from math import *\n",
    "print(cos(pi))\n",
    "print(dir())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7e371b80",
   "metadata": {},
   "outputs": [],
   "source": [
    "a = 'Life is short, you need Python'\n",
    "a.lower()              \t# 'life is short, you need Python'\n",
    "help(str.lower)\n",
    "a.upper()               \t# 'LIFE IS SHORT, YOU NEED PYTHON'\n",
    "a.count('i')            \t# 2\n",
    "a.find('e')             \t# 从左向右查找'e'，3\n",
    "a.rfind('need')         \t# 从右向左查找'need'，19\n",
    "a.replace('you', 'I')   # 'Life is short, I need Python'\n",
    "tokens = a.split()    \t# ['Life', 'is', 'short,', 'you', 'need', 'Python']\n",
    "b = ' '.join(tokens)\t# 用指定分隔符按顺序把字符串列表组合成新字符串\n",
    "c = a + '\\n'            \t# 加了换行符，注意+用法是字符串作为序列的用法\n",
    "c.rstrip()              \t# 右侧去除换行符\n",
    "[x for x in a]          \t# 遍历每个字符并生成由所有字符按顺序构成的列表\n",
    "'Python' in a   \t\t\t# True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "183a29e6",
   "metadata": {},
   "outputs": [],
   "source": [
    "a = list((1, 2, 3, 4))\n",
    "a.pop()             # 把最后一个值4从列表中移除并作为pop的返回值\n",
    "a.append(5)         # 末尾插入值，[1, 2, 3, 5]\n",
    "a.index(2)          # 找到第一个2所在的位置，也就是1\n",
    "a[2]                # 取下标，也就是位置在2的值，也就是第三个值3\n",
    "a += [4, 3, 2]      # 拼接，[1, 2, 3, 5, 4, 3, 2]\n",
    "a.insert(1, 0)      # 在下标为1处插入元素0，[1, 0, 2, 3, 5, 4, 3, 2]\n",
    "a.remove(2)         # 移除第一个2，[1, 0, 3, 5, 4, 3, 2]\n",
    "a.reverse()         # 倒序，a变为[2, 3, 4, 5, 3, 0, 1]\n",
    "a[3] = 9            # 指定下标处赋值，[2, 3, 4, 9, 3, 0, 1]\n",
    "b = a[2:5]          # 取下标2开始到5之前的子序列，[4, 9, 3]\n",
    "c = a[2:-2]         # 下标也可以倒着数，方便算不过来的人，[4, 9, 3]\n",
    "d = a[2:]           # 取下标2开始到结尾的子序列，[4, 9, 3, 0, 1]\n",
    "e = a[:5]           # 取开始到下标5之前的子序列，[2, 3, 4, 9, 3]\n",
    "f = a[:]            # 取从开头到最后的整个子序列，相当于值拷贝，[2, 3, 4, 9, 3, 0, 1]\n",
    "a[2:-2] = [1, 2, 3]  # 赋值也可以按照一段来，[2, 3, 1, 2, 3, 0, 1]\n",
    "g = a[::-1]\t    # 也是倒序，通过slicing实现并赋值，效率略低于reverse()\n",
    "a.sort()\n",
    "print(a)            # 列表内排序，a变为[0, 1, 1, 2, 2, 3, 3]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3e8fb607",
   "metadata": {},
   "outputs": [],
   "source": [
    "# random\n",
    "import random\n",
    "#a = range(10) range not support\n",
    "a = list(range(10))                 # 生成一个列表，从0开始+1递增到9\n",
    "print(a)                      # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
    "random.shuffle(a)             # shuffle函数可以对可遍历且可变结构打乱顺序\n",
    "print(a)                      # [4, 3, 8, 9, 0, 6, 2, 7, 5, 1]\n",
    "b = sorted(a)                 #  排序，默认升序\n",
    "print(b)                      # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
    "c = sorted(a, reverse=True)\n",
    "print(c)                      # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0a723c09",
   "metadata": {},
   "outputs": [],
   "source": [
    "# set\n",
    "A = set([1, 2, 3, 4])\n",
    "B = {3, 4, 5, 6}\n",
    "C = set([1, 1, 2, 2, 2, 3, 3, 3, 3])\n",
    "print(C)        # 集合的去重效果，set([1, 2, 3])\n",
    "print(A | B)    # 求并集，set([1, 2, 3, 4, 5, 6])\n",
    "print(A & B)    # 求交集，set([3, 4])\n",
    "print(A - B)    # 求差集，属于A但不属于B的，set([1, 2])\n",
    "print(B - A)    # 求差集，属于B但不属于A的，set([5, 6])\n",
    "print(A ^ B)    # 求对称差集，相当于(A-B)|(B-A)，set([1, 2, 5, 6])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5a35b745",
   "metadata": {},
   "outputs": [],
   "source": [
    "# dict\n",
    "a = {'Tom': 8, 'Jerry': 7}\n",
    "print(a['Tom'])             # 8\n",
    "b = dict(Tom=8, Jerry=7)    # 一种字符串作为键更方便的初始化方式\n",
    "print(b['Tom'])             # 8\n",
    "if 'Jerry' in a:            # 判断'Jerry'是否在keys里面\n",
    "    print(a['Jerry'])        # 7\n",
    "print(a.get('Spike'))       # None，通过get获得值，即使键不存在也不会报异常\n",
    "a['Spike'] = 10\n",
    "a['Tyke'] = 3\n",
    "a.update({'Tuffy': 2, 'Mammy Two Shoes': 42})\n",
    "print(a.values())   # dict_values([8, 2, 3, 7, 10, 42])\n",
    "print(a.pop('Mammy Two Shoes'))     # 移除'Mammy Two Shoes'的键值对，并返回42\n",
    "print(a.keys())     # dict_keys(['Tom', 'Tuffy', 'Tyke', 'Jerry', 'Spike']) \n",
    "\n",
    "# 输出 k,v\n",
    "for k, v in a.items():\n",
    "    print(\"k = {}, v = {}\".format(k,v))\n",
    "\n",
    "# 按照 insert 顺序排列的 dict \n",
    "from collections import OrderedDict\n",
    "a = {1: 2, 3: 4, 5: 6, 7: 8, 9: 10}\n",
    "b = OrderedDict({1: 2, 3: 4, 5: 6, 7: 8, 9: 10})\n",
    "print(a)    # {1: 2, 3: 4, 9: 10, 5: 6, 7: 8}\n",
    "print(b) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f503f277",
   "metadata": {},
   "outputs": [],
   "source": [
    "# file io\n",
    "import numpy as np\n",
    "with open('name_age.txt', 'w') as f: \t# 打开文件，写入模式 write\n",
    "    string = \"\"\"xiaoyang\n",
    "xiaowu\n",
    "qiqi\n",
    "zhangyuxin\"\"\"\n",
    "    # 3个双引号会使得之间的内容都成为 str 类型\n",
    "    print(string)\n",
    "    f.write(string) # 将这几行都写入文件\n",
    "    \n",
    "with open('name_age.txt', 'r') as f: \t# 打开文件，读取模式\n",
    "    print(\"open file name_age.txt\")\n",
    "    lines = f.readlines()              \t# 一次读取所有行\n",
    "    for i, line in enumerate(lines):                  \t# 按行格式化并显示信息\n",
    "        l = line[:-1]           # 去掉末尾的换行符\n",
    "        print(i, l)\n",
    "        #print('{} is {} years old.'.format(name, age))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1f3fb2ac",
   "metadata": {},
   "outputs": [],
   "source": [
    "# numpy\n",
    "import numpy as np\n",
    "a = [1, 2, 3, 4]     \t#\n",
    "b = np.array(a)         \t# array([1, 2, 3, 4])\n",
    "type(b)                         \t# <type 'numpy.ndarray'>\n",
    "print(b, type(b))\n",
    "print(b.shape)                   \t# (4,)\n",
    "print(b.argmax())               \t# 3\n",
    "print(b.max())                  \t# 4\n",
    "print(b.mean())                 \t# 2.5\n",
    "print(\"二维数组\")\n",
    "c = [[1, 2], [3, 4]]  \t# 二维列表\n",
    "d = np.array(c)         \t# 二维numpy数组\n",
    "print(d.shape)                   \t# (2, 2)\n",
    "print(d.size)                   \t# 4\n",
    "print(d.max(axis=0))            \t# 找维度0，也就是最后一个维度上的最大值，array([3, 4])\n",
    "print(d.max(axis=1))            \t# 找维度1，也就是倒数第二个维度上的最大值，array([2, 4])\n",
    "print(d.mean(axis=0))          \t# 找维度0，也就是第一个维度上的均值，array([ 2.,  3.])\n",
    "print(d.flatten())              \t# 展开一个numpy数组为1维数组，array([1, 2, 3, 4])\n",
    "print(np.ravel(c))               # 展开一个可以解析的结构为1维数组，array([1, 2, 3, 4])\n",
    "print(\"三维矩阵\")\n",
    "# 3x3的浮点型2维数组，并且初始化所有元素值为1\n",
    "e = np.ones((3, 3), dtype=np.float32)\n",
    "print(e, e.dtype)\n",
    "# 创建一个一维数组，元素值是把3重复4次，array([3, 3, 3, 3])\n",
    "f = np.repeat((2,2),3)\n",
    "print(\"2 * 2 矩阵， value = 3\", f, f.shape, f.size,f.dtype)\n",
    "# 2x2x3的无符号8位整型3维数组，并且初始化所有元素值为0\n",
    "g = np.zeros((2,3), dtype=np.uint8)\n",
    "print(g.shape,type(g.shape), g, g.size, g.dtype)                    # (2, 2, 3)\n",
    "g = g.astype(np.float64)  # 用另一种类型表示\n",
    "print(g.shape,type(g.shape), g, g.size, g.dtype)  \n",
    "l = np.arange(10)      \t# 类似range，array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n",
    "m = np.linspace(0, 6, 5)  # 等差数列，0到6之间5个取值，array([ 0., 1.5, 3., 4.5, 6.])\n",
    "p = np.array(\n",
    "    [[1, 2, 3, 4],\n",
    "     [5, 6, 7, 8]]\n",
    ")\n",
    "# np.save('p.npy', p)     # 保存到文件\n",
    "q = np.load('p.npy')    # 从文件读取\n",
    "print(q,q.dtype)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c1a5cdf6",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "# 绝对值，1\n",
    "a = np.abs(-1)\n",
    "print(a, type(a))\n",
    "# sin函数，1.0\n",
    "b = np.sin(np.pi/2)\n",
    "# tanh逆函数，0.50000107157840523\n",
    "c = np.arctanh(0.462118)\n",
    "# e为底的指数函数，20.085536923187668\n",
    "d = np.exp(3)\n",
    "# 2的3次方，8\n",
    "f = np.power(2, 3)\n",
    "# 点积，1*3+2*4=11\n",
    "g = np.dot([1, 2], [3, 4])\n",
    "# 开方，5\n",
    "h = np.sqrt(25)\n",
    "# 求和，10\n",
    "l = np.sum([1, 2, 3, 4])\n",
    "# 平均值，5.5\n",
    "m = np.mean([4, 5, 6, 7])\n",
    "# 标准差，0.96824583655185426\n",
    "p = np.std([1, 2, 3, 2, 1, 3, 2, 0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "id": "e9a8e60f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 2 3 4 5 6 7 8 9]\n",
      "[[0.08630745 0.04479364 0.67666601]\n",
      " [0.96871766 0.4258366  0.10963172]\n",
      " [0.78029236 0.32914432 0.95376133]]\n",
      " line : 4 --> [[0.07004227 0.98511995 0.41427855]\n",
      " [0.22386956 0.96840269 0.80109811]\n",
      " [0.88457847 0.94487981 0.56748535]].\n",
      "[[0.57715064 0.83551316 0.2518465 ]\n",
      " [0.33921765 0.90591102 0.24133535]\n",
      " [0.29053482 0.2046455  0.59424887]]\n",
      "5 [[0.91815491 0.46585643 0.18975191]\n",
      " [0.72693905 0.01935802 0.88374481]\n",
      " [0.42379569 0.33240952 0.7581293 ]]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "b'\\xb5Q,\\xc6\\xf5\\xf5A\\xcb\\t'"
      ]
     },
     "execution_count": 63,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# castboard\n",
    "import numpy as np\n",
    "import os, sys\n",
    "def line():\n",
    "    return sys._getframe().f_lineno\n",
    "arr1 = np.arange(1,10)\n",
    "print(arr1)\n",
    "import numpy.random as random\n",
    "print(random.random((3, 3)))\n",
    "cout(random.sample((3, 3)))\n",
    "print(random.random_sample((3, 3)))\n",
    "print(line(), random.ranf((3, 3)))\n",
    "\n",
    "# 产生10个[1,6)之间的浮点型随机数\n",
    "5*random.random(10) + 1\n",
    "random.uniform(1, 6, 10)\n",
    "# 产生10个[1,6)之间的整型随机数\n",
    "random.randint(1, 6, 10)\n",
    "# 产生2x5的标准正态分布样本\n",
    "random.normal(size=(5, 2))\n",
    "# 产生5个，n=5，p=0.5的二项分布样本\n",
    "random.binomial(n=5, p=0.5, size=5)\n",
    "a = np.arange(10)\n",
    "# 从a中有回放的随机采样7个\n",
    "random.choice(a, 7)\n",
    "# 从a中无回放的随机采样7个\n",
    "random.choice(a, 7, replace=False)\n",
    "# 对a进行乱序并返回一个新的array\n",
    "b = random.permutation(a)\n",
    "# 对a进行in-place乱序\n",
    "random.shuffle(a)\n",
    "# 生成一个长度为9的随机bytes序列并作为str返回\n",
    "# '\\x96\\x9d\\xd1?\\xe6\\x18\\xbb\\x9a\\xec'\n",
    "random.bytes(9)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ae85bd6d",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f61e08a3",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
